package com.clear.wechat.controller;

import com.clear.wechat.handler.WechatMsgFactory;
import com.clear.wechat.handler.WechatMsgHandler;
import com.clear.wechat.utils.MessageUtil;
import com.clear.wechat.utils.SHA1Util;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.util.Map;
import java.util.Objects;

/**
 * 回调Controller
 *
 *
 * todo：微信机制：首先发送get请求进行验签，相同证明token一致，接着发送post进行对接
 */
@RestController
@RequestMapping
@Slf4j
public class CallBackController {

    private static final String token = "sawfasdgfsdfsfsfd";


    @Resource
    private WechatMsgFactory wechatMsgFactory;

    @RequestMapping("test")
    public String test() {
        return "hello";
    }


    /**
     * 回调消息校验
     *
     * @param signature 微信加密签名，signature结合了开发者填写的token参数和请求中的timestamp参数、nonce参数
     * @param timestamp 时间戳
     * @param nonce     随机数
     * @param echostr   随机字符串
     * @return
     */
    @GetMapping("/callback")
    public String callBack(@RequestParam("signature") String signature,
                           @RequestParam("timestamp") String timestamp,
                           @RequestParam("nonce") String nonce,
                           @RequestParam("echostr") String echostr) {
        log.info("get验签请求参数，signature:{}, timestamp:{}, nonce:{}, echostr:{}",
                signature, timestamp, nonce, echostr);
        String shaStr = SHA1Util.getSHA1(token, timestamp, nonce, "");
        if (signature.equals(shaStr)) {
            return echostr;
        }
        return "unknown";
    }


    @PostMapping(value = "/callback", produces = "application/xml;charset=UTF-8")
    public String callBack(
            @RequestBody String requestBody,
            @RequestParam("signature") String signature,
            @RequestParam("timestamp") String timestamp,
            @RequestParam("nonce") String nonce,
            @RequestParam(value = "msg_signature", required = false) String msgSignature) {
        log.info("接收到微信消息：requestBody：{}", requestBody);

        Map<String, String> messageMap = MessageUtil.parseXml(requestBody);
        String msgType = messageMap.get("MsgType");
        String event = messageMap.get("Event");
        log.info("msgType:{}, event:{}", msgType, event);

        StringBuilder sb = new StringBuilder(msgType);
        if (!StringUtils.isEmpty(event)) {
            sb.append(".").append(event);
        }
        String msgTypeKey = sb.toString();
        log.info("msgTypeKey:{}", msgTypeKey);

        WechatMsgHandler handler = wechatMsgFactory.getHandlerByMsgType(msgTypeKey);
        if (Objects.isNull(handler)){
            return "unknown";
        }
        String replyContent = handler.dealMsg(messageMap);
        log.info("replyContent:\n{}", replyContent);
        return replyContent;
    }
}
